package com.simplenix.nicasio.admin.eb;

import com.simplenix.nicasio.persistence.HibernateUtil;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.Criteria;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.Fetch;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author fronald
 */
@Entity
@Table(name = "NIC_USU_GROUP")
public class UsuGroup implements Serializable {

	private long usuGroupId;

	private Group group;

	private User user;

	/**
	 * @return the group
	 */
	@ManyToOne(fetch = FetchType.EAGER)
	@JoinColumn(name = "GROUP_ID", insertable = true, updatable = true)
	@Fetch(org.hibernate.annotations.FetchMode.JOIN)
	@Cascade(CascadeType.ALL)
	public Group getGroup() {
		return group;
	}

	/**
	 * @param group the group to set
	 */
	public void setGroup(Group group) {
		this.group = group;
	}

	/**
	 * @return the user
	 */
	@ManyToOne(fetch = FetchType.EAGER)
	@JoinColumn(name = "USU_ID", insertable = true, updatable = true)
	@Fetch(org.hibernate.annotations.FetchMode.JOIN)
	@Cascade(CascadeType.ALL)
	public User getUser() {
		return user;
	}

	/**
	 * @param user the user to set
	 */
	public void setUser(User user) {
		this.user = user;
	}

	/**
	 * @return the usuGroupId
	 */
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "GRP_ID")
	public long getUsuGroupId() {
		return usuGroupId;
	}

	/**
	 * @param usuGroupId the usuGroupId to set
	 */
	public void setUsuGroupId(long usuGroupId) {
		this.usuGroupId = usuGroupId;
	}

	public static boolean isMember(User u, Group g) {
		Criteria c = HibernateUtil.getCurrentSession().createCriteria(UsuGroup.class.getName());
		c.add(Restrictions.eq("user", u));
		c.add(Restrictions.eq("group", g));
		int regs = (Integer) c.setProjection(Projections.rowCount()).uniqueResult();
		return regs > 0;
	}

}
